//
//  UserAccount.swift
//  微博模拟项目
//
//  Created by 尹家鑫 on 16/3/14.
//  Copyright © 2016年 尹家鑫. All rights reserved.
//
import UIKit
import AFNetworking


private let userInfoKey = "cn.itcast.account"

class UserAccount: NSObject {
    
    //定义单例对象
    static let shareAccount = UserAccount()
    
    //用于调用access_token
    var access_token: String?
    
    //access_token的生命周期，单位是秒数,当前用户token 过多少秒之后会过期
    var expires_in: NSTimeInterval = 0 {
        didSet {
            //计算过期日期
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    
    //普通用户的账户的过期日期是3天
    var expires_date: NSDate?
    
    //当前授权用户的UID。
    var uid: String?
    
    //当前登录用户的名称
    var name: String?
    
    //用户头像
    var avatar_large: String? {
        didSet {
            // 耗内存
            headImageURL = NSURL(string: avatar_large ?? "")
        }
    }
    
    
    var headImageURL: NSURL?
    
    //计算型属性
    var userLogin: Bool {
        //token不为空,就标示用户登录.token 为空就标示用户未登录
        return access_token != nil
    }
    
    //为了保证单例对象唯一.需要私有化构造函数
    override private init() {
        super.init()
        
        //加载用户信息
        self.loadUserInfo()
    }
    
    //实现过滤不存在key的方法
    override func setValue(value: AnyObject?, forUndefinedKey key: String) { }
    
    override var description: String {
        //只读属性
        let keys = ["access_token","expires_in","uid","name","avatar_large","expires_date"]
        let accountDict = self.dictionaryWithValuesForKeys(keys)
        return accountDict.description
    }
}

// 账户相关的业务逻辑的扩展
//保存数据,获取数据
extension UserAccount {
    
    //MARK:保存用户信息
    func saveUserInfo(dict: [String : AnyObject]) {
        
        
        //给当前对象KVC设置初始值 -> 未登录状态 -> 登录状态
        self.setValuesForKeysWithDictionary(dict)
        
        //保存当前对象的所有属性,已字典的形式
        let userDefaults = NSUserDefaults.standardUserDefaults()
        
        //获取当前对象的字典信息
        let keys = ["access_token","expires_in","uid","name","avatar_large"]
        let accountDict = self.dictionaryWithValuesForKeys(keys)
        
        //将用户信息保存到沙盒中,沙盒中不能够存储自定义对象
        userDefaults.setObject(accountDict, forKey: userInfoKey)
        
        //同步沙盒
        userDefaults.synchronize()
        
        //测试打印
        print(NSHomeDirectory())
    }
    
    //提供对外访问的方式
    func loadUserInfo() {
        
        //从磁盘中获取数据
        guard let dict = NSUserDefaults.standardUserDefaults().objectForKey(userInfoKey) as? [String : AnyObject] else {
            return
        }
        //将字典信息转换模型数据
        self.setValuesForKeysWithDictionary(dict)
        
        //用过期日期 和当前的日期进行比较
        if self.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            //过期日期大于当前日期
            print("token 正常")
        } else {
            print("用户token 已过期")
            self.access_token = nil
        }
    }
    
}

//用户账户相关的所有的网络请求
extension UserAccount {
    func loadAccessToken(code: String, finished: (isSuccess: Bool) -> () ) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        //参数字典
        let parameters = ["client_id" : client_id, "client_secret": client_secret,"grant_type": "authorization_code", "code": code, "redirect_uri": redirect_uri]
        
        //发起网络请求
        let AFN = AFHTTPSessionManager()
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        //发起post请求
        AFN.POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            print(result)
            print(result?.classForCoder)
            
            //获取token
            guard let dict = result as? [String : AnyObject] else {
                //失败需要执行闭包
                finished(isSuccess: false)
                return
            }
            
            //标示用户访问接口的权限的一个时效性的标识
            self.loadUserInfo(dict, finished: finished)
            }) { (_, error) -> Void in
                //失败需要执行闭包
                finished(isSuccess: false)
                print(error)
        }
    }
    
    private func loadUserInfo(dict: [String : AnyObject],finished: (isSuccess: Bool) -> ()) {
        let token = dict["access_token"] as! String
        
        //获取到用户接口访问权限之后 使用token 获取用户信息
        let uid = dict["uid"] as! String
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        //在字典中可以直接添加  nil 吗?  应该添加空对象 [NSNull null]
        let parameters = ["access_token" : token, "uid" : uid]
        let AFN = AFHTTPSessionManager()
        
        AFN.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            //接口返回的数据确定为 字典类型
            guard var userInfoDict = result as? [String : AnyObject] else {
                finished(isSuccess: false)
                return
            }
            print(userInfoDict)
            
            //1.合并字典
            for (k,v) in dict {
                
                //合并字典
                userInfoDict[k] = v
            }
            
            UserAccount.shareAccount.saveUserInfo(userInfoDict)
            
            //获取用户信息成功
            finished(isSuccess: true)
            }) { (_, error) -> Void in
                //执行失败的回调
                finished(isSuccess: false)
                print(error)
        }
    }
}